/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.danikula.videocache.HttpProxyCacheServer;
import com.srwl.mytx.converter.MyRequestBodyConverter;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.PreferenceManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MyApplication extends Application {
    private static final String TAG = "MyApplication";
    public static Context applicationContext;
    private static MyApplication instance;
    private List<Activity> activities = new ArrayList<>();
    public static int activityCount;//活动的activity计数；
    public static boolean backGround;//app 是否在后台的标识
    public static long timeOffset;//本地时间和系统时间的偏移量


    @Override
    public void onCreate() {
        //MultiDex.install(this);
        super.onCreate();
        applicationContext = this;
        instance = this;

        PreferenceManager.init(this);
        //IMClientManager.getInstance().init(this);
        // IMSClientBootstrap.getInstance().init(this);
        // *******注意********
        //Helper 必须放在 IMSClientBootstrap 之后初始化，因为自动登录 放在Helper 里面了，自动登录成功后，会调用 IMSClientBootstrap 的login 方法
        Helper.getInstance().init(this);
        AliOssService.getInstance().initAliOSS(this);
        // UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE,null);
        UMConfigure.setLogEnabled(false);
        UMConfigure.init(this,  UMConfigure.DEVICE_TYPE_PHONE, null);
        //统计SDK是否支持采集在子进程中打点的自定义事件，默认不支持
        UMConfigure.setProcessEvent(true);//支持多进程打点
        // MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        // FFmpegBridge.initJXFFmpeg(false, null);//这两个只用其中之一，暂时两个并存
        // loadFFMpegBinary();
    }


//    private void loadFFMpegBinary() {
//        try {
//
//            FFmpeg.getInstance(this).loadBinary(new LoadBinaryResponseHandler() {
//                @Override
//                public void onFailure() {
//
//                }
//            });
//        } catch (FFmpegNotSupportedException e) {
//            e.printStackTrace();
//        }
//    }

    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        MyApplication app = (MyApplication) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer(this);
    }


    public static MyApplication getInstance() {
        return instance;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // MultiDex.install(this);
    }

    public void saveActivity(Activity activity) {
        if (activity != null) {
            activities.add(activity);
        }
    }

    public void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public List<Activity> getActivities() {

        return activities;
    }

    public void finishActivities() {
        for (Activity activity : activities) {
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
        activities.clear();
    }

    public void finishActivity(Class<?> cls) {

        for (int i = 0; i < activities.size(); i++) {
            Activity activity = activities.get(i);
            if (activity.getClass().equals(cls)) {
                activity.finish();
                activities.remove(i);
                break;
            }
        }
    }

    // 创建服务用于捕获崩溃异常
    private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            //restartApp();//发生崩溃异常时,重启应用
            Log.e(TAG, "uncaughtException: " + ex.getCause().getMessage());
        }
    };

    public void onActivityStart() {
        activityCount++;
        Log.i(TAG, "onActivityStart: " + activityCount);
        if (backGround) {//如果是从后台切换到前台，重新请求下系统时间
            backGround = false;
            getServiceTime();
        }
    }

    public void onActivityStop() {
        activityCount--;
        Log.i(TAG, "onActivityStop: " + activityCount);
        if (activityCount == 0) {
            backGround = true;
        }
    }

    /**
     * 获取服务端时间
     */
    private void getServiceTime() {
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getServiceTime()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: 请求失败");
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                        }
                        timeOffset = (long) result.getData() - System.currentTimeMillis();
                        Log.i(TAG, "onResponse: 获取系统时间完成" + result.getData() + "本地时间：" + System.currentTimeMillis());
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: 获取系统时间失败");
                        t.printStackTrace();
                    }
                });
    }
}
